import React, { Component } from 'react'
import { message, Card, Form, Input, Button, Checkbox } from 'antd'
import styles from './index.module.scss'
import Logo from 'assets/logo.png'
import { login } from 'api/user.js'
import { setToken } from 'utils/storage.js'

export default class Login extends Component {
  handleFinish = async (values) => {
    try {
      const res = await login(values)
      message.success('登录成功')
      setToken(JSON.stringify(res.data))
      const { state } = this.props.location
      if (state && state.fromPath) {
        this.props.history.push(state.fromPath)
      } else {
        this.props.history.push('/home')
      }
    } catch (err) {
      message.error('登录失败')
    }
  }

  render() {
    return (
      <div className={styles.login}>
        <Card className="login-box">
          <img src={Logo} alt="" className="login-logo" />
          <Form
            name="basic"
            onFinish={this.handleFinish}
            size="large"
            validateTrigger={['onBlur', 'onChange']}
            initialValues={{
              mobile: '13800000000',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '请输入手机号!',
                },
                {
                  pattern:
                    /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                  message: '手机号格式不正确!',
                },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
                {
                  min: 6,
                  max: 6,
                  message: '请输入正确格式的验证码!',
                },
              ]}
            >
              <Input.Password placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请勾选阅读并同意')),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
